package test.netty;

import com.google.protobuf.Message;
import com.yuan.kafkastudy.constant.MessageEnum;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;

@Slf4j
public class NettyServerHandler extends ChannelInboundHandlerAdapter {

    /** 累积缓冲区，每条连接一份 */
    private final ByteBuf cum = ByteBufAllocator.DEFAULT.buffer();
    /** -1 表示还没读到长度 */
    private int length = -1;

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {

        ByteBuf in = (ByteBuf) msg;
        cum.writeBytes(in);          // 1. 累加
        in.release();

        while (cum.isReadable()) {
            /* 2. 读长度 */
            if (length == -1) {
                if (cum.readableBytes() < 4) return;
                length = cum.readInt();
                log.debug("长度域：{}", length);
            }

            /* 3. 读正文 */
            if (cum.readableBytes() < length) {
                log.info("半包等待中，还需 {} 字节", length - cum.readableBytes());
                return;
            }

            byte[] body = new byte[length];
            cum.readBytes(body);
            System.out.println("收到完整字符串：" + new String(body, StandardCharsets.UTF_8));

            /* 4. 复位，准备下一帧 */
            length = -1;

        }

        /* 5. 释放已读空间，防止内存膨胀 */
        cum.discardReadBytes();
    }
}
